import { ScrollView, View } from "@tarojs/components";
import { useSetState, useUpdateEffect } from "ahooks";

import Card from "@/components/common/Card";
import ListView from "@/components/app/ListView";
import BySearchBar from "@/components/ui/BySearchBar";
import PopupContainer from "@/components/app/PopupContainer";

import useList from "@/hooks/useList";
import ApiApp from "@/api/app";

import { ByPopupBottomEvent } from "@/components/ui/ByPopupBottom";
import ByText from "@/components/ui/ByText";
import ByRow from "@/components/ui/ByRow";
import ByCol from "@/components/ui/ByCol";
import Taro from "@tarojs/taro";

// 固定
const quotaClassCode = "001009";

export default ({
  onChange,
  onCancel,
}: { onChange: (e: any) => void } & ByPopupBottomEvent) => {
  const { list: classTree } = useList<{
    QuotaClassId: number;
    QuotaClassName: string;
    IsActive: boolean;
  }>(ApiApp.quotaClassTree, {
    defaultParams: [{ quotaClassCode }],
    onSuccess({ list }) {
      setSearch({
        quotaClassId: list[0]["QuotaClassId"],
      });
    },
  });

  const { list, loading, resetToFirst, nextPage } = useList<{
    QuotaId: number;
    QuotaName: number;
    QuotaCode: number;
    // 综合价
    QuotaPrice: number;
    // 承包价
    ContractPrice: number;
    // quotaNum:
    Unit: string;
  }>(ApiApp.quotaClassList, { manual: true });

  const [search, setSearch] = useSetState({
    keyword: "",
    quotaClassCode,
    quotaClassId: undefined as undefined | number,
  });

  useUpdateEffect(() => {
    console.log(search)
    resetToFirst(search);
  }, [search]);

  const handleSelected = async (target: any) => {
    // @ts-expect-error
    const { content, confirm } = await Taro.showModal({
      title: "输入数量",
      // @ts-expect-error
      editable: true,
      content: "0",
      placeholderText: "请输入数字",
    });

    if (confirm) {
      if (!/^-?\d+(\.\d+)?$/.test(content)) {
        Taro.showToast({ icon: "error", title: "请输入正确的数字" });
        return;
      }

      // 保留三位小数
      const QuotaNum = Number(content).toFixed(2);
      onChange({ ...target, QuotaNum: Number(QuotaNum) });
    }
  };
  return (
    <PopupContainer title="选择定额" onCancel={onCancel}>
      <View className="flex h-[75vh]">
        <ScrollView
          className="w-[200px] flex-none bg-[#f6f8fd] h-[75vh]"
          scrollY
        >
          {classTree.map((item) => (
            <View
              key={item.QuotaClassId}
              className={`flex-center h-[104px] ${search.quotaClassId === item.QuotaClassId
                  ? "bg-[#23252a] text-white"
                  : ""
                }`}
              onClick={() => setSearch({ quotaClassId: item.QuotaClassId })}
            >
              {item.QuotaClassName}
            </View>
          ))}
        </ScrollView>

        <View className="flex-auto px-3">
          <ScrollView
            scrollY
            onScrollToLower={nextPage}
            className="relative h-[75vh]"
          >
            <View className="bg-white z-20">
              <BySearchBar onConfirm={(e) => setSearch({ keyword: e })} />
            </View>

            <ListView loading={loading} isEmpty={list.length === 0}>
              {list.map((item) => (
                <Card
                  key={item.QuotaId}
                  className="my-3"
                  onClick={() => handleSelected(item)}
                >
                  <ByText bold>{item.QuotaName}</ByText>

                  <ByRow align="center">
                    <ByCol span={"auto"}>
                      <ByText size="sm" type="third">
                        {item.QuotaCode}
                      </ByText>
                    </ByCol>

                    <View className="flex flex-none">
                      <View className="flex flex-col rounded-md p-1 bg-primary text-center text-white">
                        <ByText size="xs">
                          ￥{item.ContractPrice}/{item.Unit}
                        </ByText>
                        <ByText size="xs">承包价</ByText>
                      </View>
                      <View className="ml-1 flex flex-col rounded-md p-1 bg-primary text-center text-white">
                        <ByText size="xs">
                          ￥{item.QuotaPrice}/{item.Unit}
                        </ByText>
                        <ByText size="xs">综合价</ByText>
                      </View>
                    </View>
                  </ByRow>
                </Card>
              ))}
            </ListView>
          </ScrollView>
        </View>
      </View>
    </PopupContainer>
  );
};
